package be.donovan.gui.helper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ImageIcon;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public class ImageLoader implements ResourceLoaderAware{
	
	private ResourceLoader resourceLoader;
	private String resourceBasePath = "img/"; // default value
	private Map<String,Resource> resourceMap = new HashMap<String,Resource>();
	
	private Log logger = LogFactory.getLog(getClass());
	
	private static ImageLoader instance;
	
	private ImageLoader(){}
	
	/**
	 * @param location file name
	 * @return icon an ImageIcon
	 * @throws IOException should this throw checked or unchecked exception ?
	 */
	public static ImageIcon getImageIcon(String location) {
		try {
			return getInstance().loadImageIcon(location);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
	}
	
	public void setResourceBasePath(String resourceBasePath) {
		this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");
		if(!this.resourceBasePath.endsWith("/")){
			this.resourceBasePath += "/";
		}
	}

	protected ResourceLoader getResourceLoader() {
		if(this.resourceLoader == null){
			this.resourceLoader = new DefaultResourceLoader();
		}
		return this.resourceLoader;
	}
	
	protected ImageIcon loadImageIcon(String location) throws IOException{
		logger.debug(location);
		String fullLocation = this.resourceBasePath + location;
		if(!resourceMap.containsKey(location)){
			Resource resource = getResourceLoader().getResource(fullLocation);
			if(resource.exists()){
				logger.debug(resource);
				resourceMap.put(location, resource);
			}else{
				logger.error(location);
				throw new IOException(fullLocation + "does not exist");
			}
		}
		return new ImageIcon(resourceMap.get(location).getURL());
	}

	protected static ImageLoader getInstance() {
		if(instance == null){
			instance = new ImageLoader();
		}
		return instance;
	}

}
